package actions;

import com.opensymphony.xwork2.ActionContext;

import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;

import net.sf.json.JSONObject;
import utils.JSONResponse;
import utils.Pub;

import dao.inter.Login;

public class LoginAction extends CMActionSupport implements SessionAware {
	private Logger logger = LogManager.getLogger(LoginAction.class);
	private Login login;
	private String account;
	private String password;
	private String code;
	private Map<String, Object> session;

	public String loginData() throws Exception {
		this.logger.error("\nacount:" + this.account + "\npassword:" + this.password);
		if (this.hasFieldErrors()) {
			this.logger.error("参数错误！！！");
			return NONE;
		}

		JSONObject jsonData = new JSONObject();
		boolean re = this.login.getJsonResultByAccount(account, password);
		String serverCode = (String) session.get("SESSION_SECURITY_CODE");

		if (account != null && password != null) {
			if (re && serverCode.equals(code)) {
				jsonData.put(Pub.STATUS, true);
				jsonData.put(Pub.MESSAGE, "登录成功！");
				// 写入session
				ActionContext.getContext().getSession().put("account", getAccount());
				ActionContext.getContext().getSession().put("password", getPassword());

			} else if (account.equals("")) {
				jsonData.put(Pub.STATUS, false);
				jsonData.put(Pub.MESSAGE, "请输入用户名");
			} else if (password.equals("")) {
				jsonData.put(Pub.STATUS, false);
				jsonData.put(Pub.MESSAGE, "请输入密码");
			} else {
				jsonData.put(Pub.STATUS, false);
				jsonData.put(Pub.MESSAGE, "用户名或密码错误");
			}
			if (!serverCode.equals(code)) {
				jsonData.put(Pub.STATUS, false);
				jsonData.put(Pub.MESSAGE, "验证码错误");
			} else if (serverCode.equals("")) {
				jsonData.put(Pub.STATUS, false);
				jsonData.put(Pub.MESSAGE, "请输入验证码");
			}
		}
		logger.debug("json is " + jsonData.toString());
		JSONResponse.returnJsonToResponse(jsonData);
		return NONE;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Login getLogin() {
		return login;
	}

	public void setLogin(Login login) {
		this.login = login;
	}

}
